﻿#region Using Statements
using System.Drawing;
using DirectZZT.Shared.Core;
using DirectZZT.Shared.World;
using DirectZZT.Shared.World.Objects;
using System;
using Microsoft.Xna.Framework.Graphics;
using System.IO;
using System.Drawing.Imaging;
#endregion

namespace DirectZZT.BoardObjects
{
    /// <summary>
    /// Represents the object ("Object") board object.
    /// This is one of the few ZZT-board objects that can contain one script.
    /// </summary>
    [Export("Object")]
    [BoardObject(Identifier = "Object", Classification = BoardObjectClassification.Terrain, AllowBecome = true)]
    public sealed class ObjectBoardObject : BoardObject
    {
        #region Constructors

        /// <summary>
        /// Initializes a new instance of the ObjectBoardObject class.
        /// </summary>
        public ObjectBoardObject()
            : base()
        {
            this.Enabled = true;
            this.Visible = true;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Objects can have scripts.
        /// </summary>
        /// <param name="featureSet"></param>
        /// <returns></returns>
        protected override bool CanAttachScript(FeatureSet featureSet)
        {
            return true;
        }

        /// <summary>
        /// Called when the object is spawned.
        /// </summary>
        /// <param name="modifiers"></param>
        public override void OnSpawn(string[] modifiers)
        {
            base.OnSpawn(modifiers);

            // try to read modifiers
            if (modifiers != null && modifiers.Length == 1 && modifiers[0].Length == 1)
            {
                // read char (must be of length == 1)
                char character = modifiers[0][0];
                this.Texture = character.ToString();

                // create image for this here if the resource doesn't exist yet
                if (!this.Board.World.TextureManager.ContainsResource(this.Texture))
                {
                    Bitmap image = new Bitmap(32, 32);
                    Graphics g = Graphics.FromImage(image);
                    // make the background transparent
                    g.FillRectangle(Brushes.Red, new Rectangle(0, 0, 32, 32));
                    // draw the char
                    g.DrawString(character.ToString(), new Font("Fixedsys", 14.0f), Brushes.Black, new PointF(0.0f, 0.0f));
                    // clean up
                    g.Dispose();

                    // register texture
                    using (MemoryStream ms = new MemoryStream())
                    {
                        image.Save(ms, ImageFormat.Png);
                        ms.Position = 0L;
                        this.Board.World.TextureManager.RegisterResource(this.Texture, Texture2D.FromStream(this.Board.Game.GraphicsDevice, ms));
                    }
                }
            }
        }

        #endregion
    }
}
